package echos

import (
	"net/http"
	"time";"fmt"
	"jinquan.supor.com/common"
	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)


func UserToken_ExpireHours(hours time.Duration) {

}


var (
    MySQLdbLink common.DbLink
)

func MySQL_DbLink_Construct(USERNAME string, PASSWORD string, NETWORK string, 
                        SERVER string, PORT int, DATABASE string) {
    MySQLdbLink.Username = USERNAME
    MySQLdbLink.Password = PASSWORD
    MySQLdbLink.Network  = NETWORK 
    MySQLdbLink.Server   = SERVER
    MySQLdbLink.Port     = PORT
    MySQLdbLink.Database = DATABASE
}

/* 用户验证 Handler
 使用curl发起POST测试请求
 curl -X POST http://172.24.0.244:1323/ApiUserAuth -d 'Username=ljquan;Password=abc1234'
*/
func API_UserAuth(c echo.Context) error {
    //获取POST Form, Username;Password的值
    Username := c.FormValue("Username")
    Password := c.FormValue("Password")
    fmt.Println(Username+";"+Password)

    //实际场景: 需要通过用户名查询MySQL用户信息表, 必须通过密码串核对流程
    dbw := common.MySQL_NewDbHandle(MySQLdbLink)
    AuthStr, DbErr := dbw.MySQL_UserTab_QueryPassword(Username)
    dberr := fmt.Sprintf("DB Query/> %v", DbErr); fmt.Printf("%s\n", dberr)
    
    if DbErr != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": dberr,
		})
    }

    if Password == AuthStr {
		// Set custom claims
		claims := &JwtCustomClaims{
			Username,			
			jwt.StandardClaims{	//token 有效期
				ExpiresAt: time.Now().Add(time.Minute * 3).Unix(),
			},
		}
		// Create token with claims
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return c.JSON(http.StatusOK, echo.Map{
				"error": fmt.Sprintf("%v", err),
			})
		}
		return c.JSON(http.StatusOK, echo.Map{
			"token": t,
		})
    }
	return echo.ErrUnauthorized
}

/* 用户注册 Handler
 使用curl发起POST测试请求
 curl -X POST http://172.24.0.244:1323/ApiNewRegist -d 'Username=ljquan;Password=abc1234'
*/
func API_NewRegist(c echo.Context) error {
    //获取POST Form, Username;Password的值
    Username := c.FormValue("Username")
    Password := c.FormValue("Password")
    fmt.Println(Username+";"+Password)
   
   	New := common.MysqlUserTabDesc{
    	Username: Username,
    	Password: Password,
    	Email:  Username+"@qq.com",
    	Hiredate: "2038-08-08",
    } 
 	
 	dbw := common.MySQL_NewDbHandle(MySQLdbLink)
    _,_,err := dbw.MySQL_UserTab_InsertNew(New)

    if err != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": fmt.Sprintf("%v", err),
		})
    }else {
        return c.JSON(http.StatusOK, echo.Map{
            "message": fmt.Sprintf("%s registed", Username),
        }) 
    }

    return err
}


/* 用户改密 Handler
 使用curl发起POST测试请求
 curl -X POST http://172.24.0.244:1323/ApiUserChPass -d 'Username=ljquan;Password=abc1234;Newpass=zaq12wsx'
*/
func API_UserChPass(c echo.Context) error {
    //获取POST Form, Username;Password的值
    Username := c.FormValue("Username")
    Password := c.FormValue("Password")
    Newpass := c.FormValue("Newpass")
    fmt.Println(Username+"|"+Password+"|"+Newpass)
 	
 	var err error
   //实际场景: 需要通过用户名查询MySQL用户信息表, 必须通过密码串核对流程
    dbw := common.MySQL_NewDbHandle(MySQLdbLink)
    AuthStr, DbErr := dbw.MySQL_UserTab_QueryPassword(Username)
    dberr := fmt.Sprintf("DB Query/> %v", DbErr); fmt.Printf("%s\n", dberr)
    
    if DbErr != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": dberr,
		})
    }

    if Password == AuthStr {
   		_,err = dbw.MySQL_UserTab_Update(Username, Newpass)
    }

    if err != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": fmt.Sprintf("%v", err),
		})
    } else {
        return c.JSON(http.StatusOK, echo.Map{
            "message": fmt.Sprintf("%s password changed", Username),
        })  
    }

    return err
}

/* 用户自行注销账号 Handler
 使用curl发起POST测试请求
 curl -X POST http://172.24.0.244:1323/ApiUserDel -d 'Username=ljquan;Password=abc1234'
*/
func API_UserDel(c echo.Context) error {
    //获取POST Form, Username;Password的值
    Username := c.FormValue("Username")
    Password := c.FormValue("Password")
    fmt.Println(Username+"|"+Password)
 	
 	var err error
   //实际场景: 需要通过用户名查询MySQL用户信息表, 必须通过密码串核对流程
    dbw := common.MySQL_NewDbHandle(MySQLdbLink)
    AuthStr, DbErr := dbw.MySQL_UserTab_QueryPassword(Username)
    dberr := fmt.Sprintf("DB Query/> %v", DbErr); fmt.Printf("%s\n", err)
    
    if DbErr != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": dberr,
		})
    }

    if Password == AuthStr {
   		_,err = dbw.MySQL_UserTab_DeleteOne(Username)
    }

    if err != nil {
		return c.JSON(http.StatusOK, echo.Map{
			"error": fmt.Sprintf("%v", err),
		})
    } else {
        return c.JSON(http.StatusOK, echo.Map{
            "message": fmt.Sprintf("%s deleted", Username),
        })  
    }

    return err
}